package main

import (
	"net/http"
	"time"
	"wsBulletScreen/impl"

	"github.com/gorilla/websocket"
)

var (
	upgrader = websocket.Upgrader{
		// 允许跨域
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

func wsHandler(w http.ResponseWriter, r *http.Request) {
	var (
		wsConn *websocket.Conn
		err    error
		data   []byte
		conn   *impl.Connection
	)
	// Upgrade: websocket
	if wsConn, err = upgrader.Upgrade(w, r, nil); err != nil {
		return
	}

	if conn, err = impl.InitConnection(wsConn); err != nil {
		goto ERR
	}

	go func() {
		var (
			err error
		)
		ticker := time.NewTicker(time.Second)
		for {
			select {
			case <-ticker.C:
				if err = conn.WriteMessage([]byte("heartbeat")); err != nil {
					conn.Close()
					return
				}
			}
		}
	}()

	for {
		if data, err = conn.ReadMessage(); err != nil {
			goto ERR
		}
		if err = conn.WriteMessage(data); err != nil {
			goto ERR
		}
	}

ERR:
	//todo
	conn.Close()

	// websocket Conn
	//	for {
	//		// Text Binary
	//		if _, data, err = conn.ReadMessage(); err != nil {
	//			goto ERR
	//
	//		}
	//		if err = conn.WriteMessage(websocket.TextMessage, data); err != nil {
	//			goto ERR
	//		}
	//	}
	//ERR:
	//	conn.Close()
}

func main() {
	// http://localhost:777/ws
	http.HandleFunc("/ws", wsHandler)
	http.ListenAndServe(":777", nil)
}
